# -*- coding: utf-8 -*-
"""
Created on Wed Jun  6 18:56:00 2018

@author: Administrator
"""
#%%

import os
import glob
from ..origin import Shell_script
from .processmethod import Process_method

#%%
class Create_groupmask(Shell_script):
    #作用原理：
    #参数说明：
    #参数说明：
    #返回值说明：
    #举例：
    #调用：
    #被调用：
    #bug：
    groupmask_str = r'groupmask'
    group4d_str = r'group4d'
    nzcount_str = r'_nzcount'
    def initialize_input_list(self,input_list):
        print('------------------------------------------------------------------------------') #to identify the each cycle
        if len(input_list) != 2:
            raise Exception("incompatible parameter amount ") 
        #caveat:self.previous_filename or self.present_filename is actually filepath,in the future version this should be fixed.
        self.source_dirpath = input_list[0]
        self.mnimask_filepath = input_list[1]
        
    def concat_inputs(self):
        super().concat_inputs()
        #特有的文件路径
        self.blur_filepath = self.source_dirpath + self.os_sep + self.star
        medi = glob.glob(self.blur_filepath)
        if len(medi) == 0 :
            raise Exception('there is no file in the source_dirpath')
        self.filenumb = len(medi)
        self.output_dirpath = self.source_dirpath + self.underline + self.groupmask_str
        if not os.path.exists(self.output_dirpath):
            os.makedirs(self.output_dirpath)
            
        #get the suffix of the input file
        if os.path.split(medi[0])[1].split('.nii')[1] in self.suffix_gz :
            suffix = self.suffix_gz
        else:
            suffix = self.suffix
        self.group4d_filepath = self.output_dirpath + self.os_sep + self.group4d_str + suffix
        self.nzcount_filepath = self.output_dirpath + self.os_sep + self.group4d_str + self.nzcount_str + suffix
        self.groupmask_filepath =  self.output_dirpath + self.os_sep + self.groupmask_str + suffix
    def concat_script(self):
        #cmd_1的内容：3dTcat -verb  -prefix swsubj_PET_26.nii  swsubj_*
        cmd_1 =  r'3dTcat -verb  -prefix ' + self.group4d_filepath + self.space + self.blur_filepath

        #cmd_2的内容：3dTstat -prefix CBFA_warped_26_nzcount.nii.gz -mask MNI152_T1_2mm_brain_mask.nii.gz -nzcount  CBFA_warped_26.nii.gz
        cmd_2 = r'3dTstat -prefix ' + self.nzcount_filepath  + r' -mask ' + self.mnimask_filepath + r' -nzcount ' + self.group4d_filepath
        #cmd_3的内容：3dcalc -a CBFA_warped_26_nzcount.nii.gz  -expr 'ispositive(a-25)' -prefix CBFA_warped_26_nzcount_masked26.nii.gz
        cmd_3 = r'3dcalc -a  ' + self.nzcount_filepath + r' -expr ' + self.s_quation + r'ispositive(a-' + str(self.filenumb*0.5) + r')' + self.s_quation + r' -prefix ' + self.groupmask_filepath
        
#        #cmd_4的内容：3dBrickStat -slow -count -positive  CBFA_warped_26_nzcount_masked26.nii.gz
#        self.cmd_4 = r'3dBrickStat -slow -count -positive ' + self.groupmask_filepath
        self.shell_script = cmd_1 + self.cmd_sep + cmd_2 + self.cmd_sep + cmd_3

#%%
class Limit_mask(Shell_script):
    #作用原理：
    #参数说明：
    #参数说明：
    #返回值说明：
    #举例：
    #调用：
    #被调用：
    #bug：
    lm_str = r'_LM'
    def __init__(self,input_list=[]):
        self.initialize_input_list(input_list)
        self.concat_inputs()
        
        #get the suffix of the input file
        if os.path.split(self.source_filepath_list[0])[1].split('.nii')[1] in self.suffix :
            suffix = self.suffix
        else:
            suffix = self.suffix_gz
        #get the self.output_filepath_list
        self.output_filepath_list = []
        for self.source_filepath in self.source_filepath_list:
            self.output_filepath = self.output_dirpath + self.os_sep + os.path.split(self.source_filepath)[1].replace(suffix,self.lm_str+self.linkline+str(self.limit)+suffix)
            self.output_filepath_list.append(self.output_filepath)
            
        for self.source_filepath,self.output_filepath in zip(self.source_filepath_list,self.output_filepath_list):
            self.concat_script()
            self.excute_shell_script()
    def initialize_input_list(self,input_list):
        print('------------------------------------------------------------------------------') #to identify the each cycle
        if len(input_list) != 2:
            raise Exception("incompatible parameter amount ") 
        #caveat:self.previous_filename or self.present_filename is actually filepath,in the future version this should be fixed.
        self.source_dirpath = input_list[0]
        self.limit = input_list[1]
        
    def concat_inputs(self):
        #特有的文件路径
        self.blur_filepath = self.source_dirpath + self.os_sep + self.star
        self.source_filepath_list = glob.glob(self.blur_filepath)
        if len(self.source_filepath_list) == 0 :
            raise Exception('there is no file in the source_dirpath')
        self.output_dirpath = os.path.split(self.source_dirpath)[0] + self.os_sep + os.path.split(self.source_dirpath)[1] + self.lm_str + self.linkline + str(self.limit)
        if not os.path.exists(self.output_dirpath):
            os.makedirs(self.output_dirpath)
            
    def concat_script(self):

        #cmd_1的内容：3dcalc -a CBFA_warped_26_nzcount.nii.gz  -expr 'ispositive(a-25)' -prefix CBFA_warped_26_nzcount_masked26.nii.gz
        cmd_1 = r'3dcalc -a  ' + self.source_filepath + r' -expr ' + self.s_quation + r'within(a,' + str(self.limit) + r',1)' + self.s_quation + r' -prefix ' + self.output_filepath
        
        self.shell_script = cmd_1
        
        
#%%
        
class Split_yeotemplate(Shell_script):
  
  
  dm_str = r'_divided_mask'
  def __init__(self,input_list=[]):
      self.initialize_input_list(input_list)
      self.concat_inputs()
      
      #get the suffix of the input file
      if os.path.split(self.source_filepath)[1].split('.nii')[1] in self.suffix :
          suffix = self.suffix
      else:
          suffix = self.suffix_gz
      #get the self.output_filepath_list
      self.output_filepath_list = []
      for index in self.network_index:
          self.index = index
          self.output_filepath = self.output_dirpath + self.os_sep + str(index) + suffix
          self.output_filepath_list.append(self.output_filepath)
          self.concat_script()
          self.excute_shell_script()
  def initialize_input_list(self,input_list):
      print('------------------------------------------------------------------------------') #to identify the each cycle
      if len(input_list) != 2:
          raise Exception("incompatible parameter amount ") 
      #caveat:self.previous_filename or self.present_filename is actually filepath,in the future version this should be fixed.
      self.source_filepath = input_list[0]  #r'/media/root/Elements3/XuanWu_dpabi_spm/CBF_processing_ag/mask/Yeo2011_7Networks_MNI152_FreeSurferConformed1mm_LiberalMask.nii'
      self.network_index = input_list[1]   #[1,2,3,4,5,7]

  def concat_inputs(self):
    #特有的文件路径
    self.output_dirpath = os.path.split(self.source_filepath)[0] + self.os_sep + os.path.split(self.source_filepath)[1].split('.nii')[0] + self.dm_str
    if not os.path.exists(self.output_dirpath):
        os.makedirs(self.output_dirpath)
  
  def concat_script(self):

      #cmd_1的内容：3dcalc -a CBFA_warped_26_nzcount.nii.gz  -expr 'ispositive(a-25)' -prefix CBFA_warped_26_nzcount_masked26.nii.gz
      cmd_1 = r'3dcalc -a  ' + self.source_filepath + r' -expr ' + self.s_quation + r'equals(a,' + str(self.index) + r')' + self.s_quation + r' -prefix ' + self.output_filepath
      
      self.shell_script = cmd_1
  
#%%
        
class Split_aaltemplate(Shell_script):
  #split the AAL template into sigle region mask(the region of right and left brain is in the same mask) 
  dm_str = r'_divided_mask'
  def __init__(self,input_list=[]):
      self.initialize_input_list(input_list)
      self.concat_inputs()
      
      #get the suffix of the input file
      if os.path.split(self.source_filepath)[1].split('.nii')[1] in self.suffix :
          suffix = self.suffix
      else:
          suffix = self.suffix_gz
      #get the self.output_filepath_list
      self.output_filepath_list = []
      for index in self.network_index:
          print('index:',index)
          self.index = index
          self.output_filepath = self.output_dirpath + self.os_sep + str(index) + suffix
          self.output_filepath_list.append(self.output_filepath)
          self.concat_script()
          self.excute_shell_script()
  def initialize_input_list(self,input_list):
      print('------------------------------------------------------------------------------') #to identify the each cycle
      if len(input_list) != 2:
          raise Exception("incompatible parameter amount ") 
      #caveat:self.previous_filename or self.present_filename is actually filepath,in the future version this should be fixed.
      self.source_filepath = input_list[0]  #r'/media/root/Elements3/XuanWu_dpabi_spm/CBF_processing_ag/mask/Yeo2011_7Networks_MNI152_FreeSurferConformed1mm_LiberalMask.nii'
      self.network_index = input_list[1]   #range(1,91,2)

  def concat_inputs(self):
    #特有的文件路径
    self.output_dirpath = os.path.split(self.source_filepath)[0] + self.os_sep + os.path.split(self.source_filepath)[1].split('.nii')[0] + self.dm_str
    if not os.path.exists(self.output_dirpath):
        os.makedirs(self.output_dirpath)
  
  def concat_script(self):

      #cmd_1的内容：3dcalc -a CBFA_warped_26_nzcount.nii.gz  -expr 'within(a,str(self.index),str(self.index)+1)' -prefix CBFA_warped_26_nzcount_masked26.nii.gz
      cmd_1 = r'3dcalc -a  ' + self.source_filepath + r' -expr ' + self.s_quation + r'within(a,' + str(self.index) + self.comma + str(self.index+1) + r')' + self.s_quation + r' -prefix ' + self.output_filepath
      
      self.shell_script = cmd_1

#%%
class Split_aaltemplate_1(Split_aaltemplate):
    ##split the AAL template into sigle region mask(the region of right and left brain is in the different mask) 
    def __init__(self,input_list=[]):
      self.initialize_input_list(input_list)
      self.concat_inputs()
      
      #get the suffix of the input file
      if os.path.split(self.source_filepath)[1].split('.nii')[1] in self.suffix :
          suffix = self.suffix
      else:
          suffix = self.suffix_gz
      #get the self.output_filepath_list
      self.output_filepath_list = []
      for index in self.network_index:
          print('index:',index)
          self.index = index
          self.output_filepath = self.output_dirpath + self.os_sep + str(index) + suffix
          self.output_filepath_list.append(self.output_filepath)
          self.concat_script()
          self.excute_shell_script()
      
    def concat_script(self):
  
        #cmd_1的内容：3dcalc -a CBFA_warped_26_nzcount.nii.gz  -expr 'within(a,str(self.index),str(self.index)+1)' -prefix CBFA_warped_26_nzcount_masked26.nii.gz
        cmd_1 = r'3dcalc -a  ' + self.source_filepath + r' -expr ' + self.s_quation + r'equals(a,' + str(self.index) + r')' + self.s_quation + r' -prefix ' + self.output_filepath
        
        self.shell_script = cmd_1



#%%
      
class Intersect_2mask(Shell_script):
  
  
  im_str = r'intersect_mask'
  def __init__(self,input_list=[]):
      self.initialize_input_list(input_list)
      self.concat_inputs()

      #get the self.output_filepath_list
      for mask2_filepath in self.mask2_filepath_list:
        for mask1_filepath in self.mask1_filepath_list:
          self.mask1_filepath = mask1_filepath
          self.mask2_filepath = mask2_filepath
          mask1_dirname = os.path.split(self.mask1_dirpath)[1]
#          mask2_dirname = os.path.split(self.mask2_dirpath)[1]
          mask1_filename = os.path.split(mask1_filepath)[1].replace(self.mask_suffix,'')
          mask2_filename = os.path.split(mask2_filepath)[1].replace(self.mask_suffix,'')
          output_dirpath = self.output_dirpath + self.os_sep + mask1_dirname + self.os_sep + mask2_filename
          if not os.path.exists(output_dirpath):
            os.makedirs(output_dirpath)
          self.output_filepath = output_dirpath + self.os_sep  + mask1_filename + self.underline \
                                                                    + mask2_filename + self.mask_suffix
          self.concat_script()
          self.excute_shell_script()
  def initialize_input_list(self,input_list):
      print('------------------------------------------------------------------------------') #to identify the each cycle
      if len(input_list) != 2:
          raise Exception("incompatible parameter amount ") 
      #caveat:self.previous_filename or self.present_filename is actually filepath,in the future version this should be fixed.
      self.mask1_dirpath = input_list[0]  #如：1个文件夹路径，此文件夹中包含26subject在的标准空间的灰质可能性>P的gramatter mask
      self.mask2_dirpath = input_list[1]   #如：Yeo template经过Split_yeotemplate处理后得到的7个mask文件（每一个mask文件对应一个functional network）
      
  def concat_inputs(self):
    #获取文件路径
    self.blur_filepath = self.mask1_dirpath + self.os_sep + self.star
    self.mask1_filepath_list = glob.glob(self.blur_filepath)
#    print('self.blur_filepath:',self.blur_filepath)
#    print('self.mask1_filepath_list:',self.mask1_filepath_list)
    
    self.blur_filepath = self.mask2_dirpath + self.os_sep + self.star
    self.mask2_filepath_list = glob.glob(self.blur_filepath)
    
    print('self.mask1_filepath_list:',self.mask1_filepath_list)
    print('self.mask2_filepath_list:',self.mask2_filepath_list)
    #判断两个文件夹中的mask文件的后缀是否相同，若不相同，出发异常。若相同，则将其赋给self.mask_suffix,备以后使用。
    mask1_suffix = os.path.split(self.mask1_filepath_list[0])[1].split('.nii')
    mask2_suffix = os.path.split(self.mask2_filepath_list[0])[1].split('.nii')
    print('mask1_suffix:',mask1_suffix)
    print('mask2_suffix:',mask2_suffix)
    if not mask1_suffix[1] == mask2_suffix[1]:
      raise Exception("the suffix of the file from 2 mask_dirpath must be same")
    else:
      if  mask1_suffix[1] in self.suffix :
          self.mask_suffix = self.suffix
      else:
          self.mask_suffix = self.suffix_gz

    #构造输出文件夹路径，注意输出文件夹路径是根据mask1_dirpath来构造的。
    self.output_dirpath = os.path.split(self.mask2_dirpath)[0]  + self.os_sep + self.im_str
    if not os.path.exists(self.output_dirpath):
        os.makedirs(self.output_dirpath)
  
  def concat_script(self):

      #cmd_1的内容：3dcalc -a CBFA_warped_26_nzcount.nii.gz  -expr 'ispositive(a-25)' -prefix CBFA_warped_26_nzcount_masked26.nii.gz
      cmd_1 = r'3dcalc -a  ' + self.mask1_filepath +  ' -b ' +  self.mask2_filepath  +  r' -expr ' + self.s_quation + r'(a*b)' +  self.s_quation + r' -prefix ' + self.output_filepath
      
      self.shell_script = cmd_1

#%% pick the voxel which value equal to 1
class Equal_1_E1(Process_method):
    
    def concat_script(self):
        #cmd_1的内容：3dcalc -a CBFA_warped_26_nzcount.nii.gz  -expr 'ispositive(a-25)' -prefix CBFA_warped_26_nzcount_masked26.nii.gz
        cmd_1 = r'3dcalc -a  ' + self.previous_filename + r' -expr ' + self.s_quation + r'equals(a,' + '1' + r')' + self.s_quation + r' -prefix ' + self.present_filename
        
        self.shell_script = cmd_1
        
        
#%% pick the voxel which value equal to 1
        
        
class Greater_dot5_GD5(Shell_script):
    threshold_str = 'threshold'
    threshold_value_str = '-0.5'
    def __init__(self,input_list=[]):
        self.initialize_input_list(input_list)
        self.concat_inputs()
        self.concat_script()
        self.excute_shell_script()
    def initialize_input_list(self,input_list):
        print('------------------------------------------------------------------------------') #to identify the each cycle
        if len(input_list) != 3:
            raise Exception("incompatible parameter amount ") 
        #caveat:self.previous_filename or self.present_filename is actually filepath,in the future version this should be fixed.
        self.input_filepath = input_list[0]
        self.mask_filepath = input_list[1]
        self.output_dirpath = input_list[2]
                                                          
    def concat_inputs(self):
        #get the suffix of the input file
        if os.path.split(self.input_filepath)[1].split('.nii')[1] in self.suffix :
            suffix = self.suffix
        else:
            suffix = self.suffix_gz
        
        self.output_dirpath = self.output_dirpath + self.os_sep + os.path.split(os.path.split(self.input_filepath)[0])[1] + \
                              self.underline + self.threshold_str + self.threshold_value_str
        if not os.path.exists(self.output_dirpath):
          os.makedirs(self.output_dirpath)
        
        self.output_filepath = self.output_dirpath + self.os_sep + os.path.split(self.input_filepath)[1].split(suffix)[0] + \
                                self.underline + self.threshold_str + self.threshold_value_str + suffix

    def concat_script(self):
        #cmd_1的内容：3dcalc -a CBFA_warped_26_nzcount.nii.gz  -expr 'ispositive(a-0.5)' -prefix CBFA_warped_26_nzcount_masked26.nii.gz
        cmd_1 = r'3dcalc -a  ' + self.input_filepath + ' -b ' + self.mask_filepath +  r' -expr ' + self.s_quation + r'ispositive(a*b' + self.threshold_value_str + r')' + self.s_quation + r' -prefix ' + self.output_filepath
        
        self.shell_script = cmd_1

#%% 
class Equal_2_E2(Shell_script):
    def __init__(self,input_list=[]):
        self.initialize_input_list(input_list)
        self.concat_inputs()
        
        #get the suffix of the input file
        if os.path.split(self.source1_filepath_list[0])[1].split('.nii')[1] in self.suffix :
            suffix = self.suffix
        else:
            suffix = self.suffix_gz

        for self.source1_filepath,self.source2_filepath in zip(self.source1_filepath_list,self.source2_filepath_list):
            output_dirpath = self. output_dirpath + self.os_sep + os.path.split(self.source1_dirpath)[1] + self.underline \
                              + os.path.split(self.source2_dirpath)[1]
            if not os.path.exists(output_dirpath):
                os.makedirs(output_dirpath)
            
            self.output_filepath = output_dirpath + self.os_sep + os.path.split(self.source1_filepath)[1].split(suffix)[0] + self.underline \
                                                  + os.path.split(self.source2_filepath)[1].split(suffix)[0] + suffix
                                                  
            self.concat_script()
            self.excute_shell_script()
            
    def initialize_input_list(self,input_list):
        print('------------------------------------------------------------------------------') #to identify the each cycle
        if len(input_list) != 3:
            raise Exception("incompatible parameter amount ") 
        #caveat:self.previous_filename or self.present_filename is actually filepath,in the future version this should be fixed.
        self.source1_dirpath = input_list[0]
        self.source2_dirpath = input_list[1]
        self.output_dirpath = input_list[2]
        
    def concat_inputs(self):
        #特有的文件路径
        self.source1_filepath_list = glob.glob(self.source1_dirpath + self.os_sep + self.star)
        self.source2_filepath_list = glob.glob(self.source2_dirpath + self.os_sep + self.star)
        self.source1_filepath_list.sort()
        self.source2_filepath_list.sort()
        if len(self.source1_filepath_list) != len(self.source2_filepath_list) :
            raise Exception('there is not equal number of file in two source_dirpath')
    def concat_script(self):

        #cmd_1的内容：3dcalc -a 
        cmd_1 = r'3dcalc -a  ' + self.source1_filepath +  r' -b ' + self.source2_filepath + r' -expr ' + self.s_quation + r'equals(a,b)' + self.s_quation + r' -prefix ' + self.output_filepath
        
        self.shell_script = cmd_1

#%% add two mask file.
class Add_2_A2(Shell_script):
    def __init__(self,input_list=[]):
        self.initialize_input_list(input_list)
        self.concat_inputs()
        
        #get the suffix of the input file
        if os.path.split(self.source1_filepath_list[0])[1].split('.nii')[1] in self.suffix :
            suffix = self.suffix
        else:
            suffix = self.suffix_gz

        for self.source1_filepath,self.source2_filepath in zip(self.source1_filepath_list,self.source2_filepath_list):
            output_dirpath = self. output_dirpath + self.os_sep + os.path.split(self.source1_dirpath)[1] + self.underline \
                              + os.path.split(self.source2_dirpath)[1]
            if not os.path.exists(output_dirpath):
                os.makedirs(output_dirpath)
            
            self.output_filepath = output_dirpath + self.os_sep + os.path.split(self.source1_filepath)[1].split(suffix)[0] + self.underline \
                                                  + os.path.split(self.source2_filepath)[1].split(suffix)[0] + suffix
                                                  
            self.concat_script()
            self.excute_shell_script()
            
    def initialize_input_list(self,input_list):
        print('------------------------------------------------------------------------------') #to identify the each cycle
        if len(input_list) != 3:
            raise Exception("incompatible parameter amount ") 
        #caveat:self.previous_filename or self.present_filename is actually filepath,in the future version this should be fixed.
        self.source1_dirpath = input_list[0]
        self.source2_dirpath = input_list[1]
        self.output_dirpath = input_list[2]
        
    def concat_inputs(self):
        #特有的文件路径
        self.source1_filepath_list = glob.glob(self.source1_dirpath + self.os_sep + self.star)
        self.source2_filepath_list = glob.glob(self.source2_dirpath + self.os_sep + self.star)
        self.source1_filepath_list.sort()
        self.source2_filepath_list.sort()
        if len(self.source1_filepath_list) != len(self.source2_filepath_list) :
            raise Exception('there is not equal number of file in two source_dirpath')
    def concat_script(self):

        #cmd_1的内容：3dcalc -a CBFA_warped_26_nzcount.nii.gz  -expr 'ispositive(a-25)' -prefix CBFA_warped_26_nzcount_masked26.nii.gz
        cmd_1 = r'3dcalc -a  ' + self.source1_filepath +  r' -b ' + self.source2_filepath + r' -expr ' + self.s_quation + r'(a+b)' + self.s_quation + r' -prefix ' + self.output_filepath
        
        self.shell_script = cmd_1

#%%
#    source_dirpath = r'/media/root/Elements3/XuanWu_dpabi_spm/CBF_processing_ag/CBF_clear_background_SN_SR'
#    mnimask_filepath = r'/root/Documents/BrainMask_05_61x73x61.nii'
#    Create_groupmask(source_dirpath,mnimask_filepath)
    

#    source_dirpath = r'/media/root/Elements3/XuanWu_dpabi_spm/CBF_processing_ag(old)/CBF_clear_background_SN_SR'
#    mnimask_filepath = r'/root/Documents/BrainMask_05_61x73x61.nii'
#    Create_groupmask(source_dirpath,mnimask_filepath)